package homework.five.S_5_1; // 新增的 package 声明

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Scanner;

public class DeleteDemo {

    private static final String URL = "jdbc:mysql://localhost:3306/userdb";
    private static final String DB_USERNAME = "root";
    private static final String DB_PASSWORD = "123456";

    public static void main(String[] args) {
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        Scanner scanner = new Scanner(System.in);

        try {
            // 1. 注册驱动
            Class.forName("com.mysql.cj.jdbc.Driver");

            // 2. 获取连接
            connection = DriverManager.getConnection(URL, DB_USERNAME, DB_PASSWORD);

            // 3. 编写 SQL
            String sql = "DELETE FROM userdb WHERE id = ?";

            // 4. 创建预编译语句
            preparedStatement = connection.prepareStatement(sql);

            // 5. 输入 ID
            System.out.println("请输入要删除的 ID：");
            int id = scanner.nextInt();
            preparedStatement.setInt(1, id);

            // 6. 执行更新
            int rowsAffected = preparedStatement.executeUpdate();

            // 7. 处理结果
            if (rowsAffected > 0) {
                System.out.println("删除成功！");
            } else {
                System.out.println("未找到对应 ID，删除失败！");
            }

        } catch (ClassNotFoundException e) {
            System.err.println("数据库驱动加载失败！");
            e.printStackTrace();
        } catch (SQLException e) {
            System.err.println("数据库操作异常！");
            e.printStackTrace();
        } finally {
            // 8. 关闭资源（增强健壮性）
            try {
                if (preparedStatement != null) preparedStatement.close();
                if (connection != null) connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            scanner.close();
        }
    }
}
